<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 用户提现
 * Class ConsumerCash
 * @author heyu
 */
class WithdrawCash extends MY_Controller {
	
	/**
	 * @var DlnUserModel
	 */
    public $mMuser = null;

	public function __construct(){
		parent::__construct();
        $this->loadModel('DlnUserModel', 'mMuser', 'deliveryman');
	}

	/**
	 * 首页
	 */
	public function index(){
		$data = array(
			'title' =>'提现',
			'status' => $this->getStatus()
		);
		$this->view('deliveryman/withdrawCash/home',$data,'datatable,validation,datepicker');
	}

	/**
	 * 列表
	 */
	public function getList(){
	   
		$this->db->select('a.id,u.name,u.mobile,a.amount,a.status,a.action_time,bank,a.addtime,a.refuse_remarks')
				 ->join($this->mMuser->tbUser.' u', 'u.id = a.deliveryman_id')
				 ->where('a.type', 2)
				 ->where_in('u.county_id', $this->countyItem)
				 ->order_by('a.id desc');
				 
		$data = $this->mMuser->pagination($this->mMuser->tbAmountDetails.' a');
		if(!empty($data['data'])){
			foreach ($data['data'] as $k =>$v){
				
				$tA = json_decode($v['bank'], true);
				$data['aaData'][$k][] = $v['name'].'<span style="color:grey;">（'.$v['mobile'].'）</span>';
				$data['aaData'][$k][] = is_array($tA) ? $tA['bank'].'<span style="color:grey;">（'.$tA['code'].'）<span>' : '';
				$data['aaData'][$k][] = - $v['amount'];
                $data['aaData'][$k][] = isset($v['action_time']) ? dateFormat($v['action_time'], true) : '';
                $data['aaData'][$k][] = dateFormat($v['addtime'], true);
                $tS = '';
                if($v['status'] == 3){
                	$tS = '<a href="javascript:void(0);" title="查看拒绝原因" class="view-btn">
                			<span class="content hide">'.nl2br($v['refuse_remarks']).'</span><i class="fa fa-eye"></i></a>';
                }
                $data['aaData'][$k][] = $this->getStatus($v['status'],true).$tS;
				if ($v['status'] == 1) {
                    $btnConfig = adminCreateBtn(array(
                        'label' => ' 已打款',
                        'icon' => '',
                        'attr' => array(
                            'href' => getUrl('deliveryman/withdrawCash/changeStatus') . '?id=' . $v['id'] . '&status=2',
                            'class' => 'ajax-request-btn btn default btn-xs blue-stripe',
                            'alert-message' => "确认要标记为已打款吗？"
                        ),
                        'tag' => 'a',
                    ));
                    $btnConfig .= ' ' . adminCreateBtn(array(
                        'label' => ' 拒绝',
                        'icon' => '',
                        'attr' => array(
                            'href' => 'javascript:;',
                            'class' => 'btn default btn-xs red-stripe edit-btn',
                            'data-id' => $v['id'],
                        ),
                        'tag' => 'a',
                    ));
                }else{
                    $btnConfig = '';
                }
				$data['aaData'][$k][] = $btnConfig;
			}
		}

		unset($data['data']);
		echo json_encode($data);
	}

	/**
	 * 获取状态
	 *
	 * @param	integer	$key
	 * @param	boolean	$show	是否显示
	 * @return	mixed
	 */
	public function getStatus($key = null, $show = false){

		$config = array(
            '1' => '申请中',
            '2' => '已打款',
            '3' => '已拒绝'
		);

		if($key !== null){

			if(isset($config[$key]) && ! $show){
				return $config[$key];
			}

			if(isset($config[$key]) && $show){

				if($key == 3){
					return '<span class="label label-danger">'.$config[$key].'</span>';
				}else if($key == 2){
					return '<span class="label label-success">'.$config[$key].'</span>';
				}else if($key == 1){
					return '<span class="label label-warning">'.$config[$key].'</span>';
				}
			}
			return '';
		}

		return $config;
	}

	/**
	 * 修改状态
	 */
	public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
            array('status', '状态', 'required|is_list[3,2]'),
        );
        $status = (int)get('status');
        if ($status == 3){
            $vConf[] = array('reason', '拒绝理由', 'required');
        }
        $this->formDataValidation($vConf, array(
            'id' => get('id'),
            'status' => get('status'),
            'reason' => get('reason')
        ));
		$id = get('id');
		
		$this->db->select('a.deliveryman_id,a.status,a.amount')
				 ->join($this->mMUser->tbUser.' u', 'u.id = a.deliveryman_id')
				 ->where_in('u.county_id', $this->countyItem)
				 ->where('a.id', $id)
				 ->where('a.type', 2);
        $info = $this->mMuser->getOne($this->mMuser->tbAmountDetails.' a');
        if ( ! $info){
            $this->ajaxReturn(0, '数据不存在');
        }
        if ($info['status'] != 1){
            $this->ajaxReturn(0, '已处理，不能重复操作');
        }
        $data = ['status' => $status,'action_time' => time()];
        if ($status == 3){
            $data['refuse_remarks'] = trim(get('reason'));
        }
        
        $this->db->trans_begin();
        $this->db->where('id', $id);
		if( ! $this->mMuser->update($this->mMuser->tbAmountDetails, $data)){
			$this->db->trans_rollback();
			$this->ajaxReturn(0, '保存失败');
		}
		
		if($status == 3){
			$data = [
						'deliveryman_id' => $info['deliveryman_id'],
						'amount' => -$info['amount'],
						'type' => 3,
						'status' => 2,
						'order_id' => 0,
						'addtime' => time(),
						'action_time' => time()
			];
			if( ! $this->mMuser->insert($this->mMuser->tbAmountDetails, $data)){
				$this->db->trans_rollback();
				$this->ajaxReturn(0, '保存失败');
			}
		}
		
		$this->db->trans_commit();
		$this->ajaxReturn(1, '已保存');
	}
}
